package main

import (
	"github.com/aceld/zinx/tool"
	"github.com/aceld/zinx/ziface"
	"github.com/aceld/zinx/zinx_akr_service/core"
	"github.com/aceld/zinx/zinx_modbus_tcp/api"
	log "github.com/cihub/seelog"
	//"github.com/aceld/zinx/zlog"
	"github.com/aceld/zinx/znet"
)

//当客户端建立链接的时候的hook函数
func OnConnectionAdd(conn ziface.IConnection)  {


}

//当客户端断开连接的时候的hook函数
func OnConnectionLost(conn ziface.IConnection){

	device := core.DevicesMgrObj.GetDeviceByConn(conn)
	if device !=nil{
		if device.Status !=5{
			core.DevicesMgrObj.SetStatusByPID(device.PID,2)
			log.Debugf("%s设备离线",device.PID)
			tool.UpdateDeviceStatus(device.PID,2)//离线
		}
	}

}

func SetupLogger() error {
	//dir,_ := os.Getwd()
	//kv := strings.Split(dir, "\\")
	//var parentDir string
	//if len(kv)!=0{
	//	i := 0
	//	for ;i<(len(kv)-1);i++{
	//		parentDir=parentDir+kv[i]+"\\"
	//	}
	//}
	logger, err := log.LoggerFromConfigAsFile("./config/zinx_akr_service.xml")
	if err != nil {
		return err
	}
	log.ReplaceLogger(logger)
	return err
}


func main()  {

	////设置日志前缀，主要标记当前日志模块
	//zlog.SetPrefix("MODULE")
	//
	////添加标记位
	//zlog.AddFlag(zlog.BitShortFile | zlog.BitTime)
	//zlog.Stack(" Zinx Stack! ")
	//
	////设置日志写入文件
	//zlog.SetLogFile("./log", "testfile.log")

	defer log.Flush()
	errlog := SetupLogger()

	if errlog !=nil{
		log.Info("日志模块初始化错误：",errlog)
	}

	s := znet.NewServer()

	//注册客户端连接建立和丢失函数
	s.SetOnConnStart(OnConnectionAdd)
	s.SetOnConnStop(OnConnectionLost)

	//注册路由
	s.AddRouter(0x00,&api.RegisterApi{})
	s.AddRouter(0x93,&api.TimeCalibrationApi{})
	s.AddRouter(0x89,&api.EventSetValApi{})
	s.AddRouter(0x92,&api.DataProcessApi{})
	s.AddRouter(0xdd,&api.DevicePowerOffApi{})

	//启动服务
	s.Serve()
}
